import { TaskFrame } from "../frame/taskFrame"
import { EventRoute } from "./eventRoute"
import https from 'https'
import fs from 'fs'

const routes: EventRoute[] = []

// 关闭软件
routes.push(
	new EventRoute('close-login', (api) => {
		api.mainWindow.close()
	})
)

// 拖拽窗口
routes.push(
	new EventRoute('custom-adsorption', (api, data) => {
		api.mainWindow.setBounds(data);
	})
)

// 窗口操作
routes.push(
	new EventRoute('control-window', (api, data) => {
		switch (data) {
			case 'min':
				// 最小化窗口
				api.mainWindow.minimize()
				break;
			case 'max':
				// 根据窗口当前是否全屏来设置是否为全屏状态
				api.mainWindow.setFullScreen(!api.mainWindow.isFullScreen())
				break;
			case 'close':
				// 退出应用
				api.app.exit()
				break;
			default:
				break;
		}
	})
)

// 首页窗口配置
routes.push(
	new EventRoute('resize-window', (api) => {
		//窗口大小可以修改
		api.mainWindow.setResizable(true);
		//窗口大小
		api.mainWindow.setSize(1200, 600);
		//窗口最小值
		api.mainWindow.setMinimumSize(1200, 600);
		//窗口居中
		api.mainWindow.center();
	})
)

// 退出登录
routes.push(
	new EventRoute('out-login', (api) => {
		//窗口大小
		api.mainWindow.setSize(900, 670);
		//窗口居中
		api.mainWindow.center();
		//窗口大小可以修改
		api.mainWindow.setResizable(false);
	})
)

/* 异步下载 */
// 打开新窗口
let taskWindow: TaskFrame | null = null
routes.push(
	new EventRoute('open-window-frame', (_api, data) => {
		switch (data.url) {
			case '/tasklist':
				if (!taskWindow || taskWindow.isDestroyed()) {
					taskWindow = new TaskFrame()
					taskWindow.create()
				} else {
					taskWindow.show()
				}
				break;

			default:
				break;
		}
	})
)

// 关闭窗口
routes.push(
	new EventRoute('task-close', () => {
		taskWindow!.destroy()
	})
)

// 下载
routes.push(
	new EventRoute('download-http-file', (api: { dialog: Electron.Dialog }, { url }) => {
		const fileName = url.substring(url.lastIndexOf('/') + 1)
		https.get(url, res => {
			api.dialog.showSaveDialog({
				title: '请选择保存的位置',
				defaultPath: fileName,
			}).then(result => {
				if (result.filePath) {
					const file = fs.createWriteStream(result.filePath)
					res.pipe(file)
					// 下载完成时的提示
					file.on('finish', () => {
						file.close()
						api.dialog.showMessageBox({
							title: '提示信息',
							message: '下载完成',
							type: 'info'
						})
					}).on('error', err => {
						api.dialog.showMessageBox({
							title: '提示信息',
							message: err.message,
							type: 'error'
						})
					})
				}
			})
		})
	})
)

export default routes 